﻿$.ajaxSetup({
    cache: false
});

/**
 * 通用ajax提交方法
 * 
 * @param url调用路径
 * @param param调用参数
 * @param success执行成功时的回调函数
 * @param error执行出错时的回调函数
 * @param resulttarget显示服务器错误的页面元素（jquery选择器字符串）
 * @param hideWait 是否显示等待提示
 *            
 */
function myajax(url, param, success, error, resulttarget, isJsonResult,hideWait) {
    var options = {};
    options['url'] = url;
    options['param'] = param;
    options['success'] = success;
    options['error'] = error;
    options['resulttarget'] = resulttarget;
    options['hideWait'] = hideWait;
    if (isJsonResult) {
        options['dataType'] = 'json';
    }
    else {
        options['dataType'] = '';
    }
    commonAjax(options);
}

/**
 * 通用ajax提交方法
 * 
 * @param options
 *            参数对象包含属性:url,param,callback,hideWait,dataType,target.<br/>
 *            dataType和target至少有一个为undefined
 * @returns {Boolean}
 */
function commonAjax(options) {
    $.ajaxSetup({
        cache: false
    });

    // 参数为空或者ajax请求url为空时不做任何处理
    if (options == null || !options.url) {
        return false;
    }
    // 带上csrftoken参数的处理
    var param = options.param;
    var onsuccess = options.success;
    if (typeof (onsuccess) != "function") {
        onsuccess = null;
    }

    var onerror = options.error;
    if (typeof (onerror) != "function") {
        onerror = null;
    }

    var resulttarget = options.resulttarget;
    //var _callback = options.success;
    //var callback = function (msg) {
    //    if (typeof (_callback) == "function") {
    //        _callback(msg);
    //    }
    //};

    $.ajax({
        type: "post",
        url: options.url,
        data: {parameters:param},
        dataType:'text',
        success: function (msg) {
            if (msg.indexOf('REQUESTERROR') != -1) {
                // 出错页面
                $(resulttarget).html(msg);
            } else if (msg.indexOf('USERNOTLOGINYET') != -1) {
                // session超时页面
                //window.open("/login.jsp", "_self");
            } else {
                // 正常处理

                // 返回类型是json格式
                if (options.dataType && options.dataType == 'json') {
                    //msg = "'" + msg.substr(1, msg.length - 2) + "'";
                    try {
                        msg = $.parseJSON(msg);

                        if (onsuccess != null) {
                            onsuccess(msg);
                        }
                    }
                    catch (e) { }
                }
                else {
                    if (onsuccess != null) {
                        onsuccess(msg);
                    }
                }
                //// 页面返回区域
                //if (options.target) {
                //    $(options.target).html(msg);
                //}

            }
        },
        error: function (data) {
            if (onerror != null) {
                onerror(data);
            }
            //$(resulttarget).html(data);
        }
    });
}